<template>
  <div class="comments-section">
    <!-- 评分汇总和输入框 -->
    <div class="rating-summary">
      <div class="rating-header">
        <div class="rating-score-container">
          <div class="score-box">
            <span class="sort-get-score">{{ rating }}</span>
            <span class="sort-all-score">/5</span>
          </div>
          <div class="rating-details">
            <span class="entity-name">{{ ratingComment(props.rating) }}</span>
            <span class="total-reviews">{{ totalReviews }} 条评价</span>
          </div>
        </div>
        <el-button type="primary" :icon="EditIcon" @click="scrollToParentComment" class="write-review-button">
          提交评价
        </el-button>
      </div>

      <!-- 父评论输入框 -->
      <div ref="parentCommentBox" class="parent-comment-input">
        <div class="rating-input-header">写下您的评价</div>
        <div class="rating-box">
          <el-rate
              v-model="newParentCommentScore"
              :show-score="true"
              :text-color="'#FFFFFF'"
              :colors="['#FF9999', '#FFCC66', '#99CC99']"
              score-template="{value} / 5"
              :max="5"
              :allow-half="true"
          />
        </div>
        <textarea v-model="newParentComment" placeholder="分享您的体验..." />

        <div class="upload-container">
          <el-upload
              class="upload-demo"
              action="/api/image"
              list-type="picture-card"
              :on-change="handleImageChange"
              :file-list="fileList"
              name="imageFile"
              multiple
              accept="image/*"
          >
            <div class="upload-icon">
              <el-icon><Plus /></el-icon>
              <div>添加图片</div>
            </div>
          </el-upload>
        </div>

        <div class="submit-container">
          <el-button type="primary" :icon="EditIcon" @click="submitParentComment" class="submit-review-button">
            提交评价
          </el-button>
        </div>
      </div>

      <!-- 评论筛选 -->
      <div class="filter-tabs">
        <span
            v-for="(filter, index) in filters"
            :key="index"
            :class="{ active: activeFilter === filter.type }"
            @click="applyFilter(filter.type)"
        >
          {{ filter.label }}
        </span>
      </div>
    </div>

    <!-- 评论列表 -->
    <div class="comments-list">
      <div
          v-for="(comment, index) in displayedComments"
          :key="index"
          class="comment-container"
      >
        <!-- 父评论部分 -->
        <div class="comment">
          <div class="comment-header">
            <img :src="comment.user?.avatar || defaultAvatar" class="avatar" alt="User Avatar" />
            <div class="user-info">
              <span class="username">{{ comment.user?.userName }}</span>
              <div class="rating-comment">
                <el-rate
                    v-model="comment.score"
                    disabled
                    show-score
                    text-color="#666666"
                    :colors="['#FF9999', '#FFCC66', '#99CC99']"
                    score-template="{value} / 5"
                />
                <span class="rating-comment-text">{{ ratingComment(comment.score) }}</span>
              </div>
            </div>
          </div>

          <div class="comment-body" @click="toggleReplyBox(comment)">
            <p class="comment-text" :class="{ expanded: comment.expanded }">
              {{ comment.expanded ? comment.text : truncatedText(comment.remark) }}
            </p>
            <span class="toggle-text" v-if="comment.remark?.length > 230" @click.stop="toggleComment(comment)">
              {{ comment.expanded ? '折叠评论' : '展示全部' }}
            </span>

            <div class="attached-images" v-if="comment.picture?.length > 0">
              <img
                  v-for="(img, imgIndex) in comment.picture"
                  :key="imgIndex"
                  :src="img"
                  class="thumbnail"
                  alt="Attached Image"
                  @click.stop
              />
            </div>

            <div class="like-and-time">
              <span class="like-button" @click.stop>
                <i class="fas fa-thumbs-up"></i> {{ comment.reLike }}
              </span>
              <span class="timestamp">评价日期 {{ comment.reDate }}</span>
              <span class="reply-button" @click.stop="toggleReplyBox(comment)">
                回复
              </span>
            </div>

            <!-- 父评论的子评论输入框 -->
            <div v-if="comment.showReplyBox" class="child-comment-box" @click.stop>
              <div class="child-comment-input">
                <textarea v-model="newChildrenComment" placeholder="写下你的回复..." />
                <div class="reply-actions">
                  <el-upload
                      class="upload-inline"
                      action="/api/image"
                      list-type="picture-card"
                      :on-change="handleImageChange2"
                      :file-list="fileList2"
                      name="imageFile"
                      multiple
                      accept="image/*"
                  >
                    <el-icon><Plus /></el-icon>
                  </el-upload>
                  <el-button
                      type="primary"
                      :icon="EditIcon"
                      @click="submitParentComment2(comment.remarkId)"
                      class="submit-reply-button"
                  >提交回复</el-button>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 子评论嵌套显示 -->
        <div class="child-comments" v-if="comment.comments && comment.comments.length > 0">
          <div
              class="child-comment"
              v-for="(child, childIndex) in comment.comments"
              :key="childIndex"
          >
            <div class="comment-header">
              <img :src="child.user?.avatar || defaultAvatar" class="avatar avatar-sm" alt="User Avatar" />
              <div class="user-info">
                <span class="username">{{ child.user?.userName }}</span>
              </div>
            </div>
            <div class="comment-body" @click.stop="toggleReplyBox(child)">
              <p class="comment-text">{{ child.remark }}</p>
              <div class="attached-images" v-if="child.picture?.length > 0">
                <img
                    v-for="(img, imgIndex) in child.picture"
                    :key="imgIndex"
                    :src="img"
                    class="thumbnail"
                    alt="Attached Image"
                    @click.stop
                />
              </div>
              <div class="like-and-time">
                <span class="like-button">
                  <i class="fas fa-thumbs-up"></i> {{ child.reLike }}
                </span>
                <span class="timestamp">评价日期 {{ child.reDate }}</span>
                <span class="reply-button" @click.stop="toggleReplyBox(child)">
                  回复
                </span>
              </div>

              <!-- 子评论的评论输入框 -->
              <div v-if="child.showReplyBox" class="child-comment-box" @click.stop>
                <div class="child-comment-input">
                  <textarea v-model="newChildrenComment" placeholder="写下你的回复..." />
                  <div class="reply-actions">
                    <el-upload
                        class="upload-inline"
                        action="/api/image"
                        list-type="picture-card"
                        :on-change="handleImageChange2"
                        :file-list="fileList2"
                        name="imageFile"
                        multiple
                        accept="image/*"
                    >
                      <el-icon><Plus /></el-icon>
                    </el-upload>
                    <el-button
                        type="primary"
                        :icon="EditIcon"
                        @click="submitParentComment2(child.remarkId)"
                        class="submit-reply-button"
                    >提交回复</el-button>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <hr v-if="index < displayedComments.length - 1" />
      </div>
    </div>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
          layout="prev, pager, next"
          :total="totalComments"
          :page-size="pageSize"
          :current-page="currentPage"
          @current-change="handlePageChange"
      />
    </div>
  </div>
</template>

<script setup>
import router from '@/router';
import { ref, computed, watch, defineEmits } from 'vue';
import { defineProps } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import EditIcon from './icons/EditIcon.vue';
import { useStore } from 'vuex'
import { addComment } from "@/api/comment.js";

const parentCommentBox = ref(null);
const emit = defineEmits(['doSomething2'])
const defaultAvatar = "https://via.placeholder.com/50/dddddd/666666";

const triggerParentFn = () => {
  emit('doSomething2', '参数可以是任意值')
}

const store = useStore();
function scrollToParentComment() {
  if (parentCommentBox.value) {
    parentCommentBox.value.scrollIntoView({ behavior: 'smooth' });
  }
}

const props = defineProps({
  rating: {
    type: Number,
    default: 4.8,
  },
  spot: {
    type: Object,
    required: true
  },
  totalReviews: {
    type: Number,
    default: 134994,
  },
  comments: {
    type: Array,
    default: () => [],
  },
});

const fileList = ref([]); // 图片列表绑定 v-model
const fileList2 = ref([]);

// 监听 rating
watch(
    () => props.rating,
    (newVal, oldVal) => {
      console.log('rating 发生变化:', oldVal, '=>', newVal);
    }
);

// 监听 totalReviews
watch(
    () => props.totalReviews,
    (newVal, oldVal) => {
      console.log('totalReviews 发生变化:', oldVal, '=>', newVal);
    }
);

const currentPage = ref(1);
const pageSize = ref(8);
const activeFilter = ref('all');
const newCommentText = ref('');
const newCommentImages = ref([]);
const editingComment = ref(null);
const newParentComment = ref('');
const newChildrenComment = ref('');
const uploadedImages = ref([]);
const uploadedImages2 = ref([]);
const newParentCommentScore = ref(0); // 评分初始值为0

function toggleReplyBox(comment) {
  // 设置其他评论的回复框为隐藏
  props.comments.forEach(c => {
    if (c !== comment) c.showReplyBox = false;
    if (c.comments) {
      c.comments.forEach(cc => {
        if (cc !== comment) cc.showReplyBox = false;
      });
    }
  });

  // 切换当前评论的回复框
  comment.showReplyBox = !comment.showReplyBox;
}

function handleImageChange(file, fileList) {
  console.log(`output->file`, file)
  if (file.status === 'success') {
    const imageUrl = file.response?.data;  // 获取图片路径
    if (imageUrl) {
      uploadedImages.value.push(imageUrl);
    }
  }
}

function handleImageChange2(file, fileList2) {
  console.log(`output->file`, file)
  if (file.status === 'success') {
    const imageUrl = file.response?.data;  // 获取图片路径
    if (imageUrl) {
      uploadedImages2.value.push(imageUrl);
    }
  }
}

function submitParentComment() {
  if (!newParentComment.value.trim() && !fileList.value.length) {
    ElMessage.warning('评论内容不能为空！');
    return;
  }

  if (newParentCommentScore.value === 0) {
    ElMessage.warning('请给出您的评分！');
    return;
  }

  const newComment = {
    remark: newParentComment.value,
    score: newParentCommentScore.value,
    reLike: 0,
    reDate: new Date().toLocaleDateString(),
    picture: uploadedImages.value,
    userId: store.state.userInfo.userId,
    bindId: props.spot?.spotId,
    status: 0
  };

  console.log(`output->newComment`, newComment)
  addComment(newComment).then((res) => {
    ElMessage.success({
      message: '评论提交成功！',
      type: 'success',
      duration: 2000
    });
    triggerParentFn();
  }).catch(err => {
    ElMessage.error('评论提交失败，请稍后重试');
  });

  // 重置输入
  newParentComment.value = '';
  fileList.value = [];
  uploadedImages.value = [];
  newParentCommentScore.value = 0;
}

function submitParentComment2(id) {
  if (!newChildrenComment.value.trim() && !fileList2.value.length) {
    ElMessage.warning('回复内容不能为空！');
    return;
  }

  const newComment = {
    remark: newChildrenComment.value,
    reLike: 0,
    reDate: new Date().toLocaleDateString(),
    picture: uploadedImages2.value,
    userId: store.state.userInfo.userId,
    bindId: props.spot?.spotId,
    status: 0,
    upId: id
  };

  console.log(`output->newComment`, newComment)
  addComment(newComment).then((res) => {
    ElMessage.success({
      message: '回复提交成功！',
      type: 'success',
      duration: 2000
    });
    triggerParentFn();
  }).catch(err => {
    ElMessage.error('回复提交失败，请稍后重试');
  });

  // 重置输入
  newChildrenComment.value = '';
  fileList2.value = [];
  uploadedImages2.value = [];

  // 关闭回复框
  props.comments.forEach(c => {
    c.showReplyBox = false;
    if (c.comments) {
      c.comments.forEach(cc => {
        cc.showReplyBox = false;
      });
    }
  });
}

const filters = computed(() => [
  { type: 'all', label: `全部 (${props.comments.length})` },
  { type: 'latest', label: '最新' },
  {
    type: 'withImages',
    label: `附图 (${props.comments.filter(c => c.picture?.length > 0).length})`,
  },
  {
    type: 'positive',
    label: `好评 (${props.comments.filter(c => c.score >= 4).length})`,
  },
  {
    type: 'negative',
    label: `差评 (${props.comments.filter(c => c.score <= 2).length})`,
  },
]);

const displayedComments = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  let filteredComments = props.comments;

  if (activeFilter.value === 'latest') {
    filteredComments = [...filteredComments].sort((a, b) => new Date(b.reDate) - new Date(a.reDate));
  } else if (activeFilter.value === 'withImages') {
    filteredComments = filteredComments.filter(comment => comment.picture?.length > 0);
  } else if (activeFilter.value === 'positive') {
    filteredComments = filteredComments.filter(comment => comment.score >= 4);
  } else if (activeFilter.value === 'negative') {
    filteredComments = filteredComments.filter(comment => comment.score <= 2);
  }

  return filteredComments.slice(start, end);
});

const totalComments = computed(() => {
  if (activeFilter.value === 'latest') {
    return props.comments.length;
  } else if (activeFilter.value === 'withImages') {
    return props.comments.filter(comment => comment.picture?.length > 0).length;
  } else if (activeFilter.value === 'positive') {
    return props.comments.filter(comment => comment.score >= 4).length;
  } else if (activeFilter.value === 'negative') {
    return props.comments.filter(comment => comment.score <= 2).length;
  } else {
    return props.comments.length;
  }
});

const ratingComment = (rating) => {
  if (rating > 4.5) {
    return '超赞';
  } else if (rating > 4.2) {
    return '很棒';
  } else if (rating >= 4.0) {
    return '较好';
  } else if (rating >= 3.0) {
    return '一般';
  } else {
    return '较差';
  }
};

function handlePageChange(page) {
  currentPage.value = page;
}

function applyFilter(filterType) {
  activeFilter.value = filterType;
  currentPage.value = 1; // 重置到第一页
}

function truncatedText(text) {
  const maxLength = 230;
  if (!text || text.length <= maxLength) {
    return text;
  }
  return text.slice(0, maxLength) + '...';
}

function toggleComment(comment) {
  comment.expanded = !comment.expanded;
}
</script>

<style scoped>
@import url('https://fonts.googleapis.com/css2?family=Noto+Sans+SC:wght@300;400;500;700&display=swap');
@import url('https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css');

.comments-section {
  font-family: "Noto Sans SC", sans-serif;
  margin: 0 auto;
  max-width: 1000px;
  padding: 20px;
  background-color: #FFFFFF;
  color: #333333;
}

/* 评分汇总样式 */
.rating-summary {
  margin-bottom: 30px;
  background-color: #F8F8F8;
  border-radius: 6px;
  padding: 20px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.rating-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.rating-score-container {
  display: flex;
  align-items: center;
}

.score-box {
  background-color: #666666;
  color: white;
  padding: 10px 15px;
  border-radius: 5px;
  margin-right: 15px;
  text-align: center;
}

.sort-get-score {
  font-size: 24px;
  font-weight: bold;
}

.sort-all-score {
  font-size: 16px;
  opacity: 0.8;
}

.rating-details {
  display: flex;
  flex-direction: column;
}

.entity-name {
  font-size: 20px;
  font-weight: bold;
  color: #333333;
  margin-bottom: 5px;
}

.total-reviews {
  font-size: 14px;
  color: #666666;
}

.write-review-button {
  background-color: #666666;
  border: none;
  color: white;
  padding: 8px 16px;
  border-radius: 4px;
  font-size: 14px;
}

.write-review-button:hover {
  background-color: #555555;
}

/* 父评论输入样式 */
.parent-comment-input {
  background-color: #F8F8F8;
  padding: 20px;
  border-radius: 6px;
  margin-top: 20px;
  border: 1px solid #EEEEEE;
}

.rating-input-header {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 15px;
  color: #333333;
}

.rating-box {
  background-color: #666666;
  padding: 8px 15px;
  border-radius: 4px;
  display: inline-flex;
  margin-bottom: 15px;
}

.parent-comment-input textarea {
  width: 100%;
  height: 100px;
  padding: 10px;
  border: 1px solid #DDDDDD;
  border-radius: 4px;
  font-size: 14px;
  margin-bottom: 15px;
  background-color: #FFFFFF;
}

.parent-comment-input textarea:focus {
  border-color: #666666;
  outline: none;
}

.upload-container {
  margin-bottom: 15px;
}

.upload-icon {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #666666;
}

.submit-container {
  display: flex;
  justify-content: flex-end;
}

.submit-review-button {
  background-color: #666666;
  border: none;
  padding: 8px 16px;
  color: white;
  border-radius: 4px;
  font-size: 14px;
}

.submit-review-button:hover {
  background-color: #555555;
}

/* 筛选标签样式 */
.filter-tabs {
  display: flex;
  flex-wrap: wrap;
  margin-top: 20px;
  gap: 10px;
}

.filter-tabs span {
  font-size: 14px;
  padding: 6px 12px;
  border-radius: 4px;
  cursor: pointer;
  background-color: #EEEEEE;
  color: #666666;
}

.filter-tabs span:hover {
  background-color: #E0E0E0;
}

.filter-tabs span.active {
  background-color: #666666;
  color: white;
}

/* 评论列表样式 */
.comments-list {
  margin-bottom: 30px;
}

.comment-container {
  margin-bottom: 20px;
}

.comment {
  background-color: #FFFFFF;
  border-radius: 6px;
  padding: 15px;
  border: 1px solid #EEEEEE;
}

.comment-header {
  display: flex;
  margin-bottom: 15px;
}

.avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  object-fit: cover;
  margin-right: 15px;
  border: 1px solid #EEEEEE;
}

.avatar-sm {
  width: 40px;
  height: 40px;
}

.user-info {
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.username {
  font-weight: bold;
  color: #333333;
  font-size: 16px;
  margin-bottom: 5px;
}

.rating-comment {
  display: flex;
  align-items: center;
}

.rating-comment-text {
  margin-left: 10px;
  font-weight: bold;
  font-size: 14px;
  color: #666666;
}

.comment-body {
  position: relative;
}

.comment-text {
  font-size: 14px;
  line-height: 1.6;
  color: #333333;
  margin-bottom: 15px;
  overflow: hidden;
  max-height: 120px;
}

.comment-text.expanded {
  max-height: none;
}

.toggle-text {
  color: #666666;
  cursor: pointer;
  font-size: 14px;
  display: inline-block;
  margin-bottom: 15px;
}

.toggle-text:hover {
  text-decoration: underline;
}

.attached-images {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-bottom: 15px;
}

.thumbnail {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border-radius: 4px;
  cursor: pointer;
  border: 1px solid #EEEEEE;
}

.thumbnail:hover {
  border-color: #CCCCCC;
}

.like-and-time {
  display: flex;
  align-items: center;
  margin-top: 10px;
  font-size: 14px;
}

.like-button {
  color: #666666;
  cursor: pointer;
  margin-right: 15px;
  display: inline-flex;
  align-items: center;
}

.like-button i {
  margin-right: 5px;
}

.timestamp {
  color: #999999;
  margin-right: 15px;
}

.reply-button {
  color: #666666;
  cursor: pointer;
}

.reply-button:hover {
  text-decoration: underline;
}

/* 子评论样式 */
.child-comments {
  margin-top: 15px;
  margin-left: 30px;
  border-left: 2px solid #EEEEEE;
  padding-left: 15px;
}

.child-comment {
  background-color: #F8F8F8;
  border-radius: 6px;
  padding: 15px;
  margin-bottom: 10px;
}

/* 子评论输入框样式 */
.child-comment-box {
  margin-top: 15px;
}

.child-comment-input {
  background-color: #F8F8F8;
  padding: 15px;
  border-radius: 6px;
  border: 1px solid #EEEEEE;
}

.child-comment-input textarea {
  width: 100%;
  height: 80px;
  padding: 10px;
  border: 1px solid #DDDDDD;
  border-radius: 4px;
  font-size: 14px;
  margin-bottom: 15px;
  background-color: #FFFFFF;
}

.child-comment-input textarea:focus {
  border-color: #666666;
  outline: none;
}

.reply-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.upload-inline {
  max-width: 60%;
}

.submit-reply-button {
  background-color: #666666;
  border: none;
  color: white;
  padding: 6px 12px;
  border-radius: 4px;
  font-size: 14px;
}

.submit-reply-button:hover {
  background-color: #555555;
}

/* 分页样式 */
.pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

:deep(.el-pagination.is-background .el-pager li:not(.disabled).active) {
  background-color: #666666;
  color: white;
}

:deep(.el-pagination.is-background .el-pager li:not(.disabled):hover) {
  color: #666666;
}

:deep(.el-pagination button:hover) {
  color: #666666;
}

hr {
  border: none;
  border-top: 1px solid #EEEEEE;
  margin: 20px 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .rating-header {
    flex-direction: column;
    align-items: flex-start;
  }

  .write-review-button {
    margin-top: 15px;
    align-self: flex-end;
  }

  .rating-score-container {
    margin-bottom: 15px;
  }

  .child-comments {
    margin-left: 15px;
  }

  .thumbnail {
    width: 60px;
    height: 60px;
  }

  .avatar {
    width: 40px;
    height: 40px;
  }
}
</style>